// /pages/skus/skus.js
var cart = require('../../utils/cart.js');
var wxScan = require('../../utils/wxScan.js');
var keywordapi = require('../../component/service/keywordapi.js');
var util = require('../../utils/util.js');
var jsonFormat = require('../../utils/jsonFormat.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: getApp().globalData.host,
    skus: [],
    advs:[],
    skuName: '',
    hidden: false,
    scrollTop: 0,
    scrollHeight: 0,
    page: {
      pageNo: 0,
      pageSize: 8
    },
    hasMore: true,
    orderby:'',
    sortasc:true,
    searchSkuName:'',
    searchMode:false,
    filterGroups:[],
    shadeAnimation:{},
    filterAnimation:{},
    filterParms:{},
    cloneFilterParms:{},//用于对比关闭筛选器时，选择条件是否发生变更
    expandFilter:{},
    showFilter:false,
    hasFilter:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });
    var skuName = '';
    if (typeof (options.skuName) != "undefined" && options.skuName !='undefined'){
      skuName = options.skuName;
    }
    this.setData({
      skuName: skuName
    }) 
    this.getData();
    this.getAdvs();
    wx.setNavigationBarTitle({
      title: '现货批发'
    })
  },
 
  getData:function(){
    var that = this;
    //排序目前只做价格，其他排序将来扩展
    var order = this.data.orderby;
    if(that.data.orderby=='price'){
      if(that.data.sortasc)
        order = 'price';
      else
        order = 'priceDesc';
    }
    //保存搜索关键字
    keywordapi.save(that.data.skuName);
    let params = util.obj2Url(that.data.filterParms);
    let hasFilter = false;
    if(typeof (params) == 'undefined' || params.length>1){
      hasFilter = true;
    }
    this.setData({
      hasFilter:hasFilter
    })
    wx.request({
      //url: that.data.host + 'webapp/resource/getSkus.html',
      //data: { pageSize: that.data.page.pageSize, pageNo: that.data.page.pageNo , skuName: that.data.skuName,orderPrice:orderPrice},
      url: that.data.host + 'sku/list?' + params,
      data: { pageSize: that.data.page.pageSize, pageIndex: that.data.page.pageNo ,s: that.data.skuName,sort:order},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        that.setData({
          searchSkuName: that.data.skuName
        });

        var skus = that.data.skus;

        if (res.data.records == '' || res.data.records == null || res.data.records == undefined ||res.data.records.length==0) {
          that.setData({
            hasMore: false
          });
          if(skus.length>0)
            return;
        }

        for (var i = 0; i < res.data.records.length; i++) {
          if(typeof(res.data.records[i].imgUrl)!='undefined'&&res.data.records[i].imgUrl.indexOf('img/')<2){ //处理图片兼容性
            res.data.records[i].imgUrl = getApp().globalData.imgHost + res.data.records[i].imgUrl;
          }
          if(typeof(res.data.records[i].summary)!='undefined'&&res.data.records[i].summary.indexOf('买一送一')>-1){
            res.data.records[i].promotion = true;
          }
          skus.push(res.data.records[i]);
        }

        that.data.page.pageNo++;
        that.setData({
          skus: skus,
          hidden: true,
          hasMore:true,
          filterGroups:res.data.filterGroups
        });
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },

  //获取广告banner
  getAdvs:function(){
    var that = this;
    wx.request({
      url: getApp().globalData.host + 'webapp/business/advs',
      header: getApp().globalData.header,
      data:{advType:7},
      method: 'POST',
      success: function (res) {
        if(null!=res.data&&typeof(res.data)!='undefined')
          that.setData({
            advs:res.data
          });
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },

  getSkuDetail: function (event) {
    var skuId = event.currentTarget.dataset.skuId;

    wx.navigateTo({
      url: '../sku/sku?skuId=' + skuId,
    })
  },

  //页面滑动到底部
  bindDownLoad: function () {
    var that = this;
    
    if(that.data.hasMore){
      that.getData();
      //查询期间设置为不得再次查询
      that.setData({
        hasMore: false
      });
    }
  },
   //重新查询订单列表
  queryList:function(event){    
    var clickTab = event.currentTarget.dataset.orderby;
    var datasort = false;
    if(clickTab==this.data.orderby){
      if('price'==clickTab){
        datasort = !this.data.sortasc;
      }else
        return;
    }
    //初始化当前页
    this.setData({
      hidden: false,
      skus:[],
      page:{
        pageNo:0,
        pageSize:8
      },
      hasMore: true,
      orderby:clickTab,
      sortasc:datasort
    });
    this.getData();
  },
   //搜索
  inputSearch: function (e) {
    this.setData({
      skuName: e.detail.value
    })
  },
  searchSkus:function(){
    var skuName = this.data.skuName;
    //初始化当前页
    //初始化当前页
    this.setData({
      hidden: false,
      skus:[],
      page:{
        pageNo:0,
        pageSize:8
      },
      hasMore: true,
      searchMode:false
    });
    this.getData();
  },
  //跳转至搜索页
  forwardSearch:function(){
    let that = this;
    that.setData({
      searchHistory:[]
    })
    keywordapi.history(function(res){
      that.setData({
        searchHistory:res
      })
    });
    that.setData({
      searchMode:true
    })
  },
  addShoppingCart: function(e){
    var skuIndex = e.currentTarget.dataset.skuIndex;
    cart.add(this.data.skus[skuIndex],1,true);
  },
  scanCode: function () {
    var that = this;
    wx.scanCode({
      success: function (res) {
        if ("scanCode:ok" == res.errMsg) {//扫描成功
          wxScan.wxScan(res.result);
        }
      }
    })
  },
  //选择关键词
  selectKeyword:function(e){
    this.setData({
      skuName:e.currentTarget.dataset.skuName,
      searchMode:false
    })
    this.searchSkus();
  },
  cancelSearch:function(){
     this.setData({
      skuName:'',
      searchMode:false
    })
  },
  //删除搜索历史记录
  removeHistory:function(){    
    if(this.data.searchHistory.length>0){
      let that = this;
      wx.showModal({
        title:'删除搜索历史',
        content:'确认删除所有历史搜索记录吗？',
        success: function(res) {
          if(res.confirm) {
            keywordapi.removeAll();
            that.setData({
              searchHistory:[]
            })
          }
        }
      })
    }
  },
  //选择筛选项
  selectField:function(e){
    let that = this;
    let code = e.currentTarget.dataset.code;
    let name = e.currentTarget.dataset.name;
    let filterIdx = e.currentTarget.dataset.filterIdx;
    let fieldIdx = e.currentTarget.dataset.fieldIdx;
    let hasChanged = false;
    for (let p in this.data.filterParms){
      if(p==code){
        if(this.data.filterParms[p]==name){//取消选择 , 将来可多选时，取消该分支
          this.data.filterGroups[filterIdx].fields[fieldIdx].selected = false;
          delete this.data.filterParms[p];
          //break; 加了这句会失效
          //this.data.filterParms.splice(i,1); 删除数组中的某个元素
        }else{//重新选择
          //将之前选中的field取消选中
          for(let j = 0;j < this.data.filterGroups[filterIdx].fields.length;j++){
            if(this.data.filterGroups[filterIdx].fields[j].selected){
              this.data.filterGroups[filterIdx].fields[j].selected = false;
            }
          }
          this.data.filterGroups[filterIdx].fields[fieldIdx].selected = true;
          this.data.filterParms[p] = name;
          //break; 
        }          
        hasChanged = true;
      }
    }
    if(!hasChanged){
      this.data.filterGroups[filterIdx].fields[fieldIdx].selected = true;
      this.data.filterParms[code] = name;
    }
    this.setData({
      filterParms:that.data.filterParms,
      filterGroups:that.data.filterGroups
    })
  },
  //重置筛选器
  resetFilter:function(){
    let that = this;
    for(let i = 0;i<this.data.filterGroups.length;i++){
      for(let j = 0;j<this.data.filterGroups[i].fields.length;j++){
        this.data.filterGroups[i].fields[j].selected = false;
      }
    }
    this.setData({
      filterParms:{},
      filterGroups:that.data.filterGroups
    })
  },
  //确认查询
  confirmFilter:function(){
    let that = this;
    this.createAnimetion(500);
    this.data.filterAnimation.width("1%").step();
    this.data.shadeAnimation.width("99%").step();
    this.setData({
      shadeAnimation:this.data.shadeAnimation.export(),
      filterAnimation:this.data.filterAnimation.export()
    })
    //等待动画结束
    setTimeout(function(){
      if(jsonFormat.compareObj(that.data.filterParms,that.data.cloneFilterParms)){//查询条件没有变更
        that.setData({
          showFilter:false
        })
        return;
      }
      //初始化当前页
      that.setData({
        hidden: false,
        skus:[],
        page:{
          pageNo:0,
          pageSize:8
        },
        hasMore: true,
        orderby:'',
        sortasc:true,
        showFilter:false
      });
      that.getData();
    },600)
  },
  //展开选择视图
  expandView:function(e){
    let code = e.currentTarget.dataset.code;
    if(this.data.expandFilter[code])
      this.data.expandFilter[code] = false;
    else 
      this.data.expandFilter[code] = true;
    this.setData({
      expandFilter:this.data.expandFilter
    })
  },
  //展开筛选视图
  selectFilter:function(){
    this.createAnimetion(1000);
    this.data.cloneFilterParms = jsonFormat.cloneObj(this.data.filterParms);
    this.setData({
      showFilter:true,
      cloneFilterParms:this.data.cloneFilterParms
    })
    this.data.filterAnimation.width("92%").step();
    this.data.shadeAnimation.width("8%").step();
    this.setData({
      shadeAnimation:this.data.shadeAnimation.export(),
      filterAnimation:this.data.filterAnimation.export()
    })
  },
  //创建动画对象
  createAnimetion:function(duration){
     //筛选动画
    this.data.filterAnimation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: duration,
      timingFunction: 'ease',
      // 延迟多长时间开始
      delay: 0,
      transformOrigin: '100% 0% 0'
    })

    //遮罩层动画
    this.data.shadeAnimation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: duration,
      timingFunction: 'ease',
      // 延迟多长时间开始
      delay: 0,
      transformOrigin: '100% 0% 0'
    }) 

    this.setData({
      shadeAnimation:this.data.shadeAnimation,
      filterAnimation:this.data.filterAnimation
    })
  },
  resetAll:function(){
    //初始化当前页
    this.setData({
      hidden: false,
      skus:[],
      page:{
        pageNo:0,
        pageSize:8
      },
      filterParms:{},
      skuName:'',
      hasMore: true,
      orderby:'',
      sortasc:true,
      showFilter:false
    });
    this.getData();
  },
  resetCondition:function(){
    this.resetFilter();
    this.confirmFilter();
  }
})